package com.hsgene.generator.service.impl;

import com.hsgene.common.util.idwork.SnowflakeIdWorker;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.generator.constants.GeneratorEnum;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.generator.service.GeneratorService;
import com.hsgene.generator.util.GeneratorFactory;
import com.hsgene.generator.util.generator.AbstractGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ID生成器ServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/6/28
 */
@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Autowired
    private GeneratorFactory generatorFactory;

    @Override
    public ApiResult<GeneratorDto> generate(String type, String prefix) {

        GeneratorEnum generatorType = GeneratorEnum.getEnum(type);
        GeneratorDto result = new GeneratorDto(generatorType);
        AbstractGenerator generator = generatorFactory.getGenerator(generatorType);
        result.setSerialNumber(generator.generate(prefix));

        return ApiResult.succ(result);
    }

    /**
     * 64位编号生成器
     *
     * @param prefixType   前缀
     * @param workerId     工作id
     * @param datacenterId 数据中心id
     * @return
     */
    @Override
    public ApiResult<GeneratorDto> numberGenerator(String prefixType, Integer workerId, Integer datacenterId) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(workerId, datacenterId);
        long number = idWorker.nextNumber();
        GeneratorDto result = new GeneratorDto(prefixType, prefixType.toUpperCase() + number);
        return ApiResult.succ(result);
    }
}
